var editRowsNumber,_datasDatagrid,selectForm,createDate1,createDate2,selectUsername,selectNickname,selectEmail,selectPhone,selectStatus;
var username,phone,icon,roleIds,groupIds,roleNames,groupNames,sessionID,password,passwordNew,ids;
var parentCenterTabs,dialogAddUser,formAddUser,dialogUpdatePassword,formUpdatePassword;

function addRow() {
	if (editRowsNumber != -1) {
		_datasDatagrid.datagrid('endEdit', editRowsNumber);
	} else {
		_datasDatagrid.datagrid('insertRow', {index: 0, row: {password:123}});
		_datasDatagrid.datagrid('beginEdit', 0);
		editRowsNumber = 0;
	}
}

function deleteRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录吗？', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
				}
				$.post(sy.bp()+"/admin/user/deletes", {ids:ids.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
}

function updateRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	switch (rows.length) {
	case 0:
		$.messager.alert('提示', '请选择要修改的记录', 'warning');
		break;
	case 1:
		if (editRowsNumber != -1) {
			_datasDatagrid.datagrid('endEdit', editRowsNumber);
		} else {
			var rowData = rows[0];
			$('#nicknames').val(rowData.nickname);
			$('#usernames').val(rowData.username);
			$('#id').val(rowData.id);
			$('#phone').val(rowData.phone);
			$('#emails').val(rowData.email);
			$('#logosrc').val(rowData.icon);
			if (rowData.icon) {
				$('#logoPic').attr('src', rowData.icon);
			} else {
				$('#logoPic').attr('src', sy.bp()+'/resources/css/images/logo_px.png');
			}
			dialogAddUser.dialog({title:'更新用户信息',iconCls:'icon-add',buttons:[{text:'更新',handler:dialogHandler}]});
			dialogAddUser.dialog('open');
		}
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，请每次修改一条记录', 'warning');
		break;
	}
}

function dialogHandler() {
	if (formAddUser.form('validate')) {
		var url = sy.bp() + "/admin/user/update";
		$.post(url, $('#formAddUser').serialize(), function(data) {
			if (data && data.result == 1) {
				dialogAddUser.dialog('close');
				_datasDatagrid.datagrid('reload');
				$.messager.show({
					title : '系统提示',
					msg : '提交成功!',
					timeout : 2000,
					showType : 'slide'
				});
			} else {
				$.messager.alert('系统提示', data.msg);
			}
			
		}, "json");
	}
}
/**修改用户密码*/
function updatePassNew(){
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		if(rows.length > 1){
			$.messager.alert('提示', '您选择了多个用户！', 'warning');
			_datasDatagrid.datagrid('unselectAll');
		}else{
					$('#passwordNew').val('');
					$('#ids').val(rows[0].id);
					dialogUpdatePassword.dialog({title:'修改密码',iconCls:'icon-add',buttons:[{text:'修改',handler:updatePassword},{text:'关闭',handler:function(){dialogUpdatePassword.dialog('close');_datasDatagrid.datagrid('reload');}}]});
					dialogUpdatePassword.dialog('open');
				}
	} else {
		$.messager.alert('提示', '请选择要修改密码的用户', 'error');
	}
	
}
/**修改用户密码*/
function updatePassword(){
	var url = sy.bp() + '/admin/user/';
	if (formUpdatePassword.form('validate')) {
			$.post(url + 'updatePwd', {"password":$('#passwordNew').val(),"uid":$('#ids').val()}, function(data){
				if(data && data.result ==1) {
					dialogUpdatePassword.dialog('close');
					$.messager.show({title:'系统提示', msg:data.msg, timeout:2000, showType:'slide'});
					
				} else {
					$.messager.alert('错误提示', data.msg);
				}
			},"json");
	}
}
/**重置所选记录的密码*/
function updateAllPassw(){
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确定要将当前所选择的记录重置密码吗？', function(b){
			if (b) {
				var ids = [];
				var names = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
					names.push(rows[i].username);
				}
				$.post(sy.bp()+"/admin/user/updateAllPwd", {ids:ids.join(","),names:names.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要重置密码的记录', 'error');
	}
}

/**童星管理*/
function childrenRowHandler(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择要管理童星的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/childrenStar/list?userId="+row[0].id, parentCenterTabs, row[0].username+"童星管理");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，每次只能管理一个用户', 'warning');
		break;
	}
}

/**我的消息*/
function messageRowHandler(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择查看的消息的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/message/list?userId="+row[0].id, parentCenterTabs, row[0].username+"我的消息");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，每次只能管理一个用户', 'warning');
		break;
	}
}

/**我的动态*/
function dynamicRowHandler(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择查看动态的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/dynamic/list?userId="+row[0].id, parentCenterTabs, row[0].username+"我的动态");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，每次只能管理一个用户', 'warning');
		break;
	}
}

/**我的课程*/
function courseRowHandler(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择查看课程的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/course/list?userId="+row[0].id, parentCenterTabs, row[0].username+"我的课程");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，每次只能管理一个用户', 'warning');
		break;
	}
}

/**查看我的收藏*/
function lookStore(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择要管理收藏的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/store/list?userid="+row[0].id, parentCenterTabs, row[0].nickname+"的收藏");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，每次只能查看一个用户的收藏', 'warning');
		break;
	}
}

/**试听课程*/
function CourseApplication(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择试听的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/courseapplication/list?userid="+row[0].id, parentCenterTabs, row[0].nickname+"的试听信息");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数', 'warning');
		break;
	}
}
/***意见反馈**/
function userIdeas(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择要反馈的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/ideas/list?userid="+row[0].id, parentCenterTabs, row[0].nickname+"的意见反馈");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数', 'warning');
		break;
	}
}
/**访问管理*/
function visitorRowHandler(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择要管理来访者的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/visitor/list?uid="+row[0].id+"&status=0", parentCenterTabs, row[0].nickname+"的最近访问者");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，每次只能管理一个用户', 'warning');
		break;
	}
}

/**用户组管理*/
function usergroupRowHandler(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择要管理用户组的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/group/list?uid="+row[0].id, parentCenterTabs, row[0].nickname+"的用户组");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，每次只能管理一个用户', 'warning');
		break;
	}
}

/**用户角色管理*/
function userroleRowHandler(){
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择要管理用户角色的用户', 'warning');
		break;
	case 1:
		sy.addTab(sy.bp()+"/admin/user/role/list?uid="+row[0].id, parentCenterTabs, row[0].nickname+"的用户角色");
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，每次只能管理一个用户', 'warning');
		break;
	}
}

/**开启用户帐号使用*/
function startUse(){
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确定要将当前所选择的记录开启使用吗？', function(b){
			if (b) {
				var ids = [];
				var names = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
					names.push(rows[i].nickname);
				}
				$.post(sy.bp()+"/admin/user/startUse", {ids:ids.join(","),names:names.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要开启使用的记录', 'error');
	}
}

/**停止用户帐号使用*/
function stopUse(){
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确定要将当前所选择的记录暂停使用吗？', function(b){
			if (b) {
				var ids = [];
				var names = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
					names.push(rows[i].nickname);
				}
				$.post(sy.bp()+"/admin/user/stopUse", {ids:ids.join(","),names:names.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要暂停使用的记录', 'error');
	}
}

function saveRow() {
	_datasDatagrid.datagrid('endEdit', editRowsNumber);
}

function rejectRow() {
	editRowsNumber = -1;
	_datasDatagrid.datagrid('rejectChanges');
	_datasDatagrid.datagrid('unselectAll');
}

function search_datas() {
	var formData = selectForm.form('getData', true);
	if(formData.createDate1 != '' && formData.createDate2 != '' && formData.createDate1 > formData.createDate2){
		$.messager.alert('提示', '开始时间不得大于结束时间，请重新选择！', 'warning');
	} else {
		if (selectForm.form('validate')) {
			_datasDatagrid.datagrid('load',sy.serializeObject(selectForm));
		}
	}
};

function reset_datas() {
	selectForm.find('input[type="text"]').val('');
	createDate1.datebox('setValue', '');
	createDate2.datebox('setValue', '');
	selectUsername.val('');
	selectNickname.val('');
	selectEmail.val('');
	selectPhone.val('');
	selectStatus.combobox('setValue', 0);
	
	username.val('');
	nickname.val('');
	email.val('');
	_datasDatagrid.datagrid('load',{});
}

$(function(){
	parentCenterTabs = parent.centerTabs;
	formAddUser= $('#formAddUser');
	dialogAddUser= $('#dialogAddUser');
	editRowsNumber = -1;
	_datasDatagrid = $('#_datasDatagrid');
	selectForm = $('#selectForm');
	ids=$('#ids').val();
	ttcid=$('#ttcid').val();
	dialogUpdatePassword=$('#dialogUpdatePassword');
	formUpdatePassword=$('#formUpdatePassword');
	createDate1 = $('#createDate1').datebox({editable:false}).datebox('activeTextArrow');
	createDate2 = $('#createDate2').datebox({editable:false}).datebox('activeTextArrow');
	selectUsername = $('#selectUsername').validatebox({});
	selectNickname = $('#selectNickname').validatebox({});
	selectEmail = $('#selectEmail').validatebox({});
	selectPhone = $('#selectPhone').validatebox({});
	selectStatus = $('#selectStatus').combobox({valueField:'code',textField:'name',editable:false,
		url:sy.bp() + "/admin/dictionary/listDictionary?name=启用状态"
	}).combobox('activeTextArrow');
	phone=$('#phone');
	userstore=$('#userstore');
	eduideas=$('#eduideas').val();
	icon=$('#icon');
	sessionID=$('#sessionID').val();
	password=$('#password').val();
	phone.validatebox({required:true,editable:true,validType:['mobile']});
	nickname = $('#nicknames').validatebox({required:true,editable:true,validType:['maxLength[8]']});
	username = $('#usernames').validatebox({required:true,editable:true,validType:['maxLength[30]']});
	email = $('#emails').validatebox({required:true,editable:true,validType:['email']});
	$('#passwordNew').validatebox({required:true,editable:true,validType:['length[3,16]']});
	icon.uploadify({
		method:'post',
		swf:sy.bp() + '/resources/uploadify/uploadify.swf',		//FLash文件路径
		uploader:sy.bp() + '/admin/fileUpload/upload', 			//处理文件上传Action
		fileObjName:'file',										//上传文件后台接收参数
		auto:true,                                  			//选择文件后是否自动上传，默认为true
		formData:{'sessionID':sessionID,'uploadPath':'logo'},
		buttonText:'上传LOGO',                                 	//按钮文本
        queueSizeLimit:1,                          				//队列最多可上传文件数量，默认为999
        multi:false,                                 			//是否为多选，默认为true
        removeCompleted:true,                       			//是否完成后移除序列，默认为true
        fileSizeLimit:'10MB',                       			//单个文件大小，0为无限制，可接受KB,MB,GB等单位的字符串值
        fileTypeDesc:'Image Files',                 			//文件描述
        fileTypeExts:'*.gif; *.jpg; *.png;',					//上传的文件后缀过滤器
        onUploadSuccess:function(file, data, response) {
        	var resObj = $.parseJSON(data);
            if (resObj.result == 1) {
            	$('#logoPic').attr('src', sy.bp() + '/resources/upload/logo/' + resObj.obj);
            	$('#logosrc').val(resObj.obj);
            } else {
            	$.messager.alert('警告', data.msg, 'warning');
            }
        }
    });
	
	formUpdatePassword.form({});
	dialogUpdatePassword = $('#dialogUpdatePassword').show().dialog({
		resizable : false,
		closed : true,
		closable : true,
		modal : true,
	});
	
	formAddUser.form({});
	dialogAddUser = $('#dialogAddUser').show().dialog({
		resizable : false,
		closed : true,
		closable : true,
		modal : true,
	});
	
	_datasDatagrid.datagrid({
		url : sy.bp()+'/admin/user/list',
		fit : true,
		autoRowHeight : false,
		striped : true,
		rownumbers : true,
		pagination : true,
		singleSelect : false,
		fitColumns : true,
		pageSize : 10,
		pageList : [10,20,30,40,50],
		nowrap : false,
		border : false,
		idField : 'id',
		sortName : 'id',
		sortOrder : 'desc',
		view: sy.myview,
        emptyMsg: '没有查询到相关数据',
		toolbar: [
					{text:'',iconCls: 'icon-add',handler: addRow},'-',
					{text:'',iconCls: 'icon-remove',handler: deleteRow},'-',
					{text:'',iconCls: 'icon-edit',handler: updateRow},'-',
					{text:'',iconCls: 'icon-save',handler: saveRow},'-',
					{text:'',iconCls: 'icon-redo',handler: rejectRow},'-',
					{text:'',iconCls: 'icon-cancel',handler: stopUse},'-',
					{text:'',iconCls: 'icon-accept',handler: startUse},'-',
					{text:'重置密码',iconCls: 'icon-edit',handler: updateAllPassw},'-',
					{text:'童星',iconCls: 'icon-user',handler: childrenRowHandler},'-',
					{text:'消息',iconCls: 'icon-application_view_list',handler: messageRowHandler},'-',
					{text:'动态',iconCls: 'icon-lightning',handler: dynamicRowHandler},"-",
					{text:'收藏',iconCls: 'icon-folder',handler:lookStore},'-',
					{text:'预约',iconCls: 'icon-report',handler:CourseApplication},'-',
					{text:'课程',iconCls: 'icon-folder_database',handler:courseRowHandler},'-',
					{text:'反馈',iconCls: 'icon-folder',handler:userIdeas},'-',
					{text:'来访者',iconCls: 'icon-group',handler: visitorRowHandler},'-',
					{text:'查看组',iconCls: 'icon-group_go',handler: usergroupRowHandler},'-',
					{text:'查看角色',iconCls: 'icon-user_green',handler: userroleRowHandler},'-',
					{text:'刷新',iconCls: 'icon-reload',handler: function(){_datasDatagrid.datagrid('reload');}}
				 ],
		frozenColumns: [[
		     				{field:'id',title:'编号',align:'center',width:100,sortable:true,checkbox:true},
		     				{field:'ttcid',title:'中间编号',align:'center',width:100,sortable:true,checkbox:true,hidden:true},
							{field:'username',title:'用户名',align:'left',width:100,sortable:true,editor:{type:'validatebox',options:{required:true,validType:['username']}}},
							{field:'nickname',title:'昵称',align:'left',width:100,sortable:true,editor:{type:'validatebox',options:{required:true,validType:['unnormal','maxLength[200]']}}}
					   ]],
		columns:[[
		          	{field:'phone',title:'手机号',align:'center',width:100,sortable:true,editor:{type:'validatebox',options:{required:true,validType:['mobile']}}},
					{field:'email',title:'邮箱',align:'left',width:150,sortable:true,editor:{type:'validatebox',options:{required:true,validType:['email']}}},
					{field:'createTime',title:'注册时间',align:'left',width:150,sortable:true},
					{field:'ttcid',title:'ttcid',align:'left',width:150,hidden:true},
					{field:'status',title:'状态',align:'center',width:100,sortable:true,
						formatter:function(value,row,index){
								if (value && value == -1){
								return '<span style="color:red;">停用</span>';
							} else {
								return '<span style="color:green;">启用</span>';
							}
						}
					}
				]],
		onLoadSuccess : function(data) {
			editRowsNumber = -1;
			$.messager.progress('close');
		},
		onDblClickRow : function(rowIndex, rowData) {
			if (editRowsNumber != -1) {
				_datasDatagrid.datagrid('endEdit', editRowsNumber);
			} else {
				_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
				updateRow();
			}
		},
		onRowContextMenu : function(e, rowIndex, rowData){
			e.preventDefault();
			_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
			$('#datagridContextMenu').menu('show', {left:e.pageX,top:e.pageY});
		},
		onAfterEdit : function(rowIndex, rowData, changes) {
			var inserted = _datasDatagrid.datagrid('getChanges', 'inserted');
			var updated = _datasDatagrid.datagrid('getChanges', 'updated');
			if (inserted.length < 1 && updated.length < 1) {
				editRowsNumber = -1;
				_datasDatagrid.datagrid('unselectAll');
				return;
			}
			var url='';
			if (inserted.length > 0) {
				url=sy.bp()+'/admin/user/add';
			}
			if (updated.length > 0) {
				url=sy.bp()+'/admin/user/update';
			}
			$.post(url, rowData, function(data) {
				if (data && data.result==1) {
					_datasDatagrid.datagrid('acceptChanges');
					$.messager.show({msg:data.msg,title:'系统提示'});
					_datasDatagrid.datagrid('reload');
				} else {
					_datasDatagrid.datagrid('rejectChanges');
					$.messager.alert('错误', data.msg, 'warning');
				}
				editRowsNumber = -1;
				_datasDatagrid.datagrid('unselectAll');
			}, "json");
		}
	});
});